import axios from 'axios'
import { Toast } from 'vant'
import { setStorage } from '@/common/js/utils'
import router from '../router'

axios.defaults.baseURL = 'http://lblbc.cn'
axios.defaults.withCredentials = true
axios.defaults.headers['Authorization'] = localStorage.getItem('token') || ''
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.post['Content-Type'] = 'application/json'

axios.interceptors.response.use(resp => {
  if (typeof resp.data !== 'object') {
    Toast.fail('服务器繁忙，请稍后再试')
    return Promise.reject(resp)
  }
  if (resp.data.code != 0) {
    if (resp.data.msg) Toast.fail(resp.data.msg)
    if (resp.data.code == 416) {
      router.push({ path: '/login' })
    }
    if (resp.data.data && window.location.hash == '#/login') {
      setStorage('token', resp.data.data)
      axios.defaults.headers['Authorization'] = resp.data.data
    }
    return Promise.reject(resp.data)
  }

  return resp.data
})

export default axios